package zsc.ruanc.practicaltraining.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;
import zsc.ruanc.practicaltraining.config.interceptor.tokenInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * 解决跨域
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Value("${cbs.imagesPath.file}")
    private String resPath;

    /**
     * 解决跨域问题
     * @param registry
     */
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //这里：是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                .allowedHeaders("*")
                //跨域允许时间
                .maxAge(3600);
    }

    /**
     * 跨域配置后swagger2可能不能访问，需要增加如下配置
     * @param registry
     */
    // 静态资源全部放行
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/templates/");
        registry.addResourceHandler("/res/**").addResourceLocations("file:" + resPath);
    }

    /**
     * 拦截token的bean
     * @return
     */
    @Bean
    public tokenInterceptor token() {
        return new tokenInterceptor();
    }

    /**
     * 拦截器配置拦截规则
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(token())
//                .addPathPatterns("/**")
//                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
//                .excludePathPatterns("/login", "/user/create", "/user/findPassword", "/test/**", "/error", "/user/getInfo")
//                .excludePathPatterns("/email/sendCode", "/email/sendFindPasswordCode")
//                .excludePathPatterns("/article/get/{id}", "/article/vagueQuery", "/article/userArticleList", "/article/recommend")
//                .excludePathPatterns("/comment/commentPage", "/class/selectAll", "/class/getNameList")
//                .order(100);
    }


}